package com.zy.cloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: UserHystrixService
 * @Description: #TODO
 * @Author: yanzy
 * @Date: 2021/3/3 21:42
 */
@Service
public class UserHystrixService {

    // ===================  服务降级

    public String reqOk(Integer id) {

        return "当前线程: " + Thread.currentThread().getName() + "-reqOk:" + id + "^_^";
    }

    /**
     * 服务降级: 设置超时时间3s 若程序执行实现超过3s, 或者异常 自动降级交给fallbackMethod 指向的方法执行处理
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "reqTimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String reqTimeOut(Integer id) {
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "当前线程: " + Thread.currentThread().getName() + "-reqTimeOut:" + id + "o(╥﹏╥)o";
    }

    /**
     * 降级方法
     * @param id
     * @return
     */
    public String reqTimeOutHandler(Integer id) {

        return "当前线程: " + Thread.currentThread().getName() + "系统繁忙, 请稍后重试-reqTimeOutHandler: " + id + "^_^";
    }

    // =============   服务熔断
    @HystrixCommand(fallbackMethod = "reqTimeOutHandler", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),  // 开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")   // 失败率达到多少后跳闸
    })
    public String openCircuitBreaker(Integer id) {

        if (id < 0) {
            throw new RuntimeException("id值不能为负数");
        }

        String s = IdUtil.simpleUUID();

        return Thread.currentThread().getName() + "\t 调用成功，流水号: " + s;
    }
}
